var DepartHome = {
	departCode : $("#departCode").val(),
	drgType : $("#drgType").val(),
	departDesc : $("#departDesc").val()==null||$("#departDesc").val()==""?"全院":$("#departDesc").val(),
	tableIndex: $("#departCode").val()==null||$("#departCode").val()==""?"科室":"主管医师" //表格第一列描述
};
$(function () {
	//病种
	$('#drgType').combobox({
		data:$.parseJSON($("#entityMap").val()),
		valueField:'value',
		textField:'text',
		defaultFilter: 6
	});

	var ajax = new $ax("/sds/common/groupListByDeptId", function(data){
		$('#medicalGroup').combobox({
			data:data,
			valueField:'value',
			textField:'text',
			defaultFilter: 6,
			onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
				$(this).combobox("setValue", "");
			}
		});
	},function(data){
		layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
	});
	ajax.set({"deptId":$('#departCode').val(),"id":"medicalGroup"});
	ajax.start();

	DepartHome.init();
	//主页最上面文字描述
	$("#homeHtmlDesc").panel({title:DepartHome.departDesc+"在院指标"});
	//表格上面文字描述
	$("#homeTableDesc").panel({title:DepartHome.departDesc+"在院患者数据"});
	//绑定顶部和中部蓝色数字的点击事件
	$(".homeCaseDeatil").click(function(){
		var _this = $(this);
		var key = _this.attr("id");
		var desc = _this.parent().parent().next().children().html();//父级的上一个同级元素
		DepartHome.homeKeyDetail(key,desc,DepartHome.departCode,"",1);
	});

	if(DepartHome.departDesc!='全院'){
		$(".departGroup").hide();
	}else{
		$(".departGroup").show();
	}
});

/**
 * //根据父级机构 查询子机构
 */
DepartHome.officeChange = function(that){
	var ajax = new $ax("/sds/common/deptListByHospId", function(data){
		$('#depart').combobox({
			data:data,
			valueField:'value',
			textField:'text',
			defaultFilter: 6,
			onLoadSuccess: function () { //加载完成后,val[0]写死设置选中第一项
				$(this).combobox("setValue", "");
			}
		});
	},function(data){
		layer.msg("查询失败!" + data.responseJSON.message + "!",{icon: 2});
	});
	ajax.set({"hospID":that.value,"id":"depart"});
	ajax.start();
}


DepartHome.init = function (){
	DepartHome.initTopMiddle();//加载主页顶部和中部的数据
	DepartHome.initBottomTable();//加载主页低部表格数据
};
/**
 * 加载主页顶部和中部的数据
 */
DepartHome.initTopMiddle = function(){
	var drgType = $('#drgType').combobox('getValue');
	var medicalGroup = $('#medicalGroup').combobox('getValue');
	var doctor = $('#doctor').val();//主治医生

	//获取主页顶部和中部的数据
	var param = {};
	var ajax = new $ax("/api/departhome/homeData", function (data) {
		DepartHome.writeTopData(data);
		DepartHome.drawMiddleChart(data);
    }, function (data) {
    });
	param.depart = DepartHome.departCode;//科室ID
	param.medicalGroup = medicalGroup;
	param.drgType = drgType;
	param.doctor = doctor;
	ajax.set(param);
    ajax.start();
};
/**
 * 加载主页底部表格数据
 */
DepartHome.initBottomTable = function(){
	var drgType = $('#drgType').combobox('getValue');
	var medicalGroup = $('#medicalGroup').combobox('getValue');
	var doctor = $('#doctor').val();//主治医生
	//获取主页底部表格数据
	var param = {};
	var ajax = new $ax("/api/departhome/selectAllDepartData", function (data) {
		DepartHome.drawTable(data);
    }, function (data) {
    });
	param.depart = DepartHome.departCode;//科室ID
	param.medicalGroup = medicalGroup;
	param.drgType = drgType;
	param.doctor = doctor;
	ajax.set(param);
    ajax.start();
};

/**
 * 写主页顶部数据
 */
DepartHome.writeTopData = function(data){
	$("#qcCase").html(data.qcCase);
	$("#qcCaseRate").html(MathMethod(data.qcCase, data.inCase));
	$("#qcCaseNum").html(data.qcCaseNum);
	$("#inCase").html(data.inCase);
	$("#inCaseRate").html(MathMethod(data.inCase, data.allCase));
	$("#drgNum").html(data.drgNum);
	$("#allCase").html(data.allCase);
};
/**
 * 画中部图形
 */
DepartHome.drawMiddleChart = function(data){
	echarts.init($("#drgChart")[0]).dispose();
	var chartParams = {
			backgroundColor : '#ffffff',
			isHorizontal : false,
			legendShow : false,
			showLabel : true,
			legend:{
				show : false
			}
		};
	//病种分布 饼图
	pieCharts($("#drgChart"),data.drgPieData,"",null,chartParams);
	//患者分布 条形图 纵向
	echarts.init($("#patientChart")[0]).dispose();
	lines = [
		{desc:'人次数',data:[],code:'qcNum'}
	];
	chartParams.grid={
		containLabel: true, //注意加上，否则axisLabel有可能显示会不全
		top:"30px",
		left:"5px",
		right:"5px",
		bottom:"5px"
	};
	chartParams.label={
		show:true,
		position:'top'
	};
	barChartVte($("#patientChart"), lines, data.patientBarData, "",null,chartParams);
	//医生分布 条形图 横向
	echarts.init($("#doctorChart")[0]).dispose();
	lines = [
             {desc:'质控人次数',data:[],code:'qcNum'}
             ];
	chartParams.grid={
		containLabel: true, //注意加上，否则axisLabel有可能显示会不全
        top:"30px",
        left:"5px",
        right:"5px",
        bottom:"5px"
	};
	chartParams.isHorizontal = true;
	chartParams.label.position = 'right';
	barChartVte($("#doctorChart"), lines, data.doctorBarData, "",null,chartParams);
};

/**
 * 表格的表头
 */
DepartHome.columns = [
				{title: DepartHome.tableIndex, field: 'doctorName', align: 'left', valign: 'middle', sortable: false,
					footerFormatter:function(value){
						return "";
					}
				},
				{title: '病种名称', field: 'drgName', align: 'left', valign: 'middle', sortable: false,
					formatter:function(value,row,index){
						return "<a onclick='DepartHome.homeKeyDetail(&apos;drgDetail&apos;,&apos;"+DepartHome.departDesc+
							"&apos;,&apos;"+DepartHome.departCode+"&apos;,&apos;"+row.drgId+"&apos;,2)'>"+value+"</a>";
					},
					footerFormatter:function(value){
						return "总计";
					}
				},
				{title: '入组例数', field: 'inCaseNum', align: 'left', valign: 'middle', sortable: false,
					footerFormatter:function(value){
						return DepartHome.sumFieldValue(value,"inCaseNum");
					}
				},
				{title: '质控例数', field: 'qcCaseNum', align: 'left', valign: 'middle', sortable: false,
					footerFormatter:function(value){
						return DepartHome.sumFieldValue(value,"qcCaseNum");
					}
				},
				{title: '质控人次', field: 'qcCaseTri', align: 'left', valign: 'middle', sortable: false,
					footerFormatter:function(value){
						return DepartHome.sumFieldValue(value,"qcCaseTri");
					}
				},
				{title: '平均在院天数', field: 'avgAdmDays', align: 'left', valign: 'middle', sortable: false,
					footerFormatter:function(value){
						return DepartHome.sumFieldValue(value,"preventNum");
					}
				}
                ];
/**
 * 科室详细信息
 */
DepartHome.homeDepartDetail = function(departCode,departDesc){
	var drgType = $('#drgType').combobox('getValue');
	var medicalGroup = $('#medicalGroup').combobox('getValue');
	var href = "/api/departhome?departCode="+departCode+"&departDesc="+departDesc+"&medicalGroup="+medicalGroup+"&drgType="+drgType;
	layer.open({
		type: 2,
		title: ['<i class = "fa fa-list-ol"></i>&nbsp;'+departDesc+'详细','padding-left:20px'],
		area:["98%","98%"],
		scrollbar: false,//为了禁止父页面滚动条滚动
		skin:'classfyLBStyle layer-ext-hisui',
		content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
	});
	
	//Sys.addTabPage($.trim(departDesc+"详细"), href,true);
};
/**
 * 钻取主页蓝色数字详细信息
 */
DepartHome.homeKeyDetail = function(key,desc,departCode, drgCode, type){
	var drgType = $('#drgType').combobox('getValue');
	var medicalGroup = $('#medicalGroup').combobox('getValue');
	var doctor = $('#doctor').val();//主治医生

	//type=1是从顶部蓝色数字传入，type=2表示从下面表格传入
	if(type==2){
		var href = "/api/departhome/to_case?key="+key+"&depart="+departCode+"&medicalGroup="+medicalGroup+"&drgType="+drgCode+"&doctor="+doctor+"&desc="+desc;
	}else{
		var href = "/api/departhome/to_case?key="+key+"&depart="+DepartHome.departCode+"&medicalGroup="+medicalGroup+"&drgType="+drgType+"&doctor="+doctor+"&desc="+desc;
	}
	
	layer.open({
		type: 2,
		title: ['<i class = "fa fa-list-ol"></i>&nbsp;'+desc,'padding-left:20px'],
		area:["90%","90%"],
		scrollbar: false,//为了禁止父页面滚动条滚动
		skin:'classfyLBStyle layer-ext-hisui',
		content: href //这里content是一个URL，如果你不想让iframe出现滚动条，你还可以content: ['http://sentsin.com', 'no']
	});
	//Sys.addTabPage($.trim(desc), href,true);
};

DepartHome.openCaseDetail = function (date){
	var drgType = $('#drgType').combobox('getValue');//病种
	var medicalGroup = $('#medicalGroup').combobox('getValue');
	var doctor = $('#doctor').val();//主治医生
	var index = layer.open({
		type: 2,
		title: ['<i class = "fa fa-line-chart"></i>&nbsp;触发质控项患者详细数据','padding-left:20px'],
		area: ['1300px', '500px'], //宽高
		fix: false, //不固定
		//maxmin: true,
		content: '/analysis/qcportal/to_QcCaseDetail?depart='+DepartHome.departCode+"&medicalGroup="+medicalGroup+'&entityType='+drgType+'&doctor='+doctor
	});
};

/**
 * 计算表格最后一列数据和
 */
DepartHome.sumFieldValue = function(value,field){
	var count = 0;
	for(var i in value){
		count += value[i][field];
	}
	if(count==0){//如果是0返回空
		return "0"
	}
	return count;
};

/**
 * 绘制主页的表格
 */
DepartHome.drawTable = function(tableData){
	$('#doctorTable').bootstrapTable("destroy");
	this.$table = 
		$('#doctorTable').bootstrapTable({
		data:tableData,
		striped: false,//是否显示行间隔色
		pagination: true,//是否显示分页
		showFooter: false,
		paginationLoop: false,
		pageSize : 10,//用于设置每页初始显示的条数
		pageList :[10,20,30,50,100],
		sidePagination: 'client',//设置在哪进行分页，默认”client”，可选”server”,返回数据模板不同
		sortName: "patientNum",
        sortOrder: 'desc',// desc  asc 
		maintainSelected: true,//设为true 为选中的状态
		cache: false,
		search: false, //搜索框
		columns: DepartHome.columns,
		onPostHeader: function(){  //当<thead></thead>中的内容被加载完后或者在你所用的DOM中有定义则被触发
			// $(".th-inner").css("font-weight","700");//表头字体加粗
			$("#doctorTable > tbody td").each(function(index){//鼠标悬浮 显示表格数据
        		$(this).attr("title",$(this).text());
        	});
        },
		onLoadSuccess: function(){
			var data = $('#doctorTable').bootstrapTable('getData', true);
			//合并单元格
			mergeCells(data, "doctorName", 1, $('#doctorTable'));
		}
	});
	var data = $('#doctorTable').bootstrapTable('getData', true);
	//合并单元格
	mergeCells(data, "doctorName", 1, $('#doctorTable'));
};

/**
 * 导出主页的表格数据
 */
DepartHome.exportTable = function() {
	$("#tableDiv table").tableExport(
		{
			type : 'xlsx',
			escape : 'false'
		},DepartHome.getSystemTime()+DepartHome.departDesc+'VTE指标统计表'
	)
};
/**
 * 获取当天年月日
 */
DepartHome.getSystemTime = function(){
	function p(s) {
		return s < 10 ? '0' + s: s;
	}
	var date = new Date(); // 获取中国标准时间
	var y = date.getFullYear(); // 年
	var m = date.getMonth()+1; // 月
	var d = date.getDate(); // 日
	var sysTime = y+'-'+p(m)+'-'+p(d);
	return sysTime;
};
/**
 * 计算比率 
 */
function MathMethod(a,b){
	if(b==0){
		return "0%";
	}
	var num = a/b;
	num = (num.toFixed(4)) * 100;  // 输出结果为 2.45
	var numStr = num.toString()
	var index = numStr.indexOf('.');
	if(index > -1){
		numStr = numStr.substring(0, index+3);
	}
	return numStr+"%";
}
/**
 * 合并单元格
 * @param data 原始数据（在服务端完成排序）
 * @param fieldName 合并属性名称
 * @param colspan 合并列
 * @param target 目标表格对象
 */
function mergeCells(data,fieldName,colspan,target){
	//声明一个map计算相同属性值在data对象出现的次数和
	var sortMap = {};
	for(var i = 0 ; i < data.length ; i++){
		for(var prop in data[i]){
			if(prop == fieldName){
				var key = data[i][prop]
				if(sortMap.hasOwnProperty(key)){
					sortMap[key] = sortMap[key] * 1 + 1;
				} else {
					sortMap[key] = 1;
				}
				break;
			}
		}
	}
	var index = 0;
	for(var prop in sortMap){
		var count = sortMap[prop] * 1;
		$(target).bootstrapTable('mergeCells',{index:index, field:fieldName, colspan: colspan, rowspan: count});
		index += count;
	}
}